<template>
  <el-card title="新增采购单">
    <div class="required-note">* 为必填项</div>

    <!-- 基本信息区域 -->
    <el-form
      ref="purchaseFormRef"
      :model="purchaseForm"
      :rules="formRules"
      label-width="120px"
      class="basic-info-form"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="采购单号" prop="purchaseId">
            <el-input v-model="purchaseForm.purchaseId"  ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据类型" prop="orderType">
            <el-select v-model="purchaseForm.orderType" placeholder="请选择入库类别">
              <el-option label="常规采购" value="1"></el-option>
              <el-option label="紧急采购" value="2"></el-option>
              <el-option label="退货采购" value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
       
      </el-row>

      <!-- 供应商信息区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="供应商ID" prop="vendorId">
            <el-input
              v-model="purchaseForm.vendorId"
              @blur="handleSupplierIdBlur"
              placeholder="输入供应商ID后自动填充"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商名称" prop="vendorName">
            <el-input v-model="purchaseForm.vendorName" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="purchaseForm.contactPerson" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="电话" prop="phone">
            <el-input v-model="purchaseForm.phone" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态" prop="state">
              <el-select v-model="purchaseForm.state" placeholder="请选择状态" style="width: 120px;" clearable >
                <el-option label="已入库" value="1" />
                <el-option label="已取消" value="2" />
                <el-option label="采购中" value="3" />
              </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否入账" prop="refund">
            <el-select v-model="purchaseForm.refund" placeholder="请选择是否入账">
              <el-option label="是" value="是"></el-option>
              <el-option label="否" value="否"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="description">
            <el-input v-model="purchaseForm.description" type="textarea" :rows="2" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 产品列表区域 -->
    <div class="product-list-section">
      <el-card title="产品信息">
        <el-table
          ref="productTableRef"
          :data="productList"
          border
          style="width: 100%"
          @selection-change="handleProductSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="productCode" label="产品编码" width="120"></el-table-column>
          <el-table-column prop="productName" label="产品名称" width="400"></el-table-column>
          <el-table-column prop="specifications" label="规格" width="150"></el-table-column>
          <el-table-column prop="specifications" label="单位" width="150"></el-table-column>
          <el-table-column prop="price" label="单价" width="150" align="right">
            <template #default="scope">{{ scope.row.price }}</template>
          </el-table-column>
             <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button
                type="text"
                size="small"
                class="delete-btn"
                @click="removeSelectedProduct(scope.row.productId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 已选产品区域 -->
    <div class="selected-products-section">
      <el-card title="已选产品">
        <el-table
          v-if="selectedProducts.length > 0"
          :data="selectedProducts"
          border
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="productCode" label="产品编码" width="120"></el-table-column>
          <el-table-column prop="productName" label="产品名称" width="400"></el-table-column>
          <el-table-column prop="specifications" label="规格" width="150"></el-table-column>
          <el-table-column prop="unitId" label="单位" width="150"></el-table-column>
          <el-table-column prop="price" label="单价" width="150" >
            <template #default="scope">{{ scope.row.price  }}</template>
          </el-table-column>
          <el-table-column prop="num" label="数量" align="center">
        <template #default="scope">
          <el-input-number
            v-model.number="scope.row.num"
            :min="1"
            :precision="0"
            @change="handleQuantityChange(scope.row)"
            placeholder="输入数量"
          />
        </template>
      </el-table-column>
        <el-table-column prop="total" label="总价" >
        <template #default="scope">
          {{ scope.row.total.toFixed(2) }}
        </template>
      </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button
                type="text"
                size="small"
                class="delete-btn"
                @click="removeSelectedProduct(scope.row.productId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-else class="no-products-tip">暂无选中产品</div>
      </el-card>
    </div>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button >重置</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElCard, ElRow, ElCol, ElMessage, ElTable, ElTableColumn, ElSelect, ElOption, ElDatePicker, ElInputNumber } from 'element-plus';
import type { FormInstance, FormRules, TableProps } from 'element-plus';
import axios from 'axios';

// 表单引用
const purchaseFormRef = ref<FormInstance>();
const productTableRef = ref<InstanceType<typeof ElTable>>();
import { useCounterStore } from '@/stores/counter';
const pinia=useCounterStore();

// 表单数据
const purchaseForm = reactive({
  "purchaseId": "",
  "productName": "",
  "productId": '',
  "productSpecs": "",
  "unitId": '',
  "price": 0,
  "num": 0,
  "total": 0,
  "vendorId": '',
  "vendorName": "",
  "orderType": "",
  "contactPerson": "",
  "phone": "",
  "description": "",
  "state": '',
  "recorded": true,
  "refund": "否",
 
});

// 产品数据
const productList = ref<any[]>([]);
const selectedProducts = ref<any[]>([]);
const isLoading = ref(false);

// 表单验证规则
const formRules = reactive<FormRules>({
  orderType: [{ required: true, message: '请选择单据类型', trigger: 'change' }],
  vendorId: [
    { required: true, message: '请输入供应商ID', trigger: 'blur' },
    { pattern: /^\d+$/, message: '供应商ID必须为数字', trigger: 'blur' }
  ],
  supplierName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
  receivingDate: [{ required: true, message: '请选择收货日', trigger: 'change' }]
});

const handleQuantityChange = (product: any) => {
  // 确保单价和数量都是数字
  const price = Number(product.price) || 0;
  const quantity = Number(product.num) || 0;
  // 计算总价并绑定到采购单的total字段
  product.total = price * quantity;
};
import Purchase from '@/http/PurSale';
// 获取所有产品列表
const fetchProductList = async () => {
  isLoading.value = true;
  try {
    const response = await http.get("/scmreadconsul/api/Sale/GetSaleProduct");
    if (response.data.code === 200 ) {
        productList.value = response.data.datas || [];
     } else {
      ElMessage.warning('获取产品列表失败');
    }
    
  } catch (error) {
    ElMessage.error('获取产品列表时发生错误');
    console.error('获取产品列表错误:', error);
  } finally {
    isLoading.value = false;
  }
};

// 处理供应商
const handleSupplierIdBlur = async () => {
  if (!purchaseForm.vendorId) return;

  try {
   http.get("/scmreadconsul/api/Purchases/GetVendor",{params:{SupplierId:purchaseForm.vendorId}}).then(response=>{
    if (response.data.code === 200) {
      purchaseForm.vendorName = response.data.data.supplierName;
      purchaseForm.contactPerson = response.data.data.supplierContact;
      purchaseForm.phone = response.data.data.supplierTel;
      purchaseForm.description=response.data.data.supplierRemark;
    } else {
      ElMessage.warning('未找到该供应商信息');
    
    }
   })
    
  } catch (error) {
    ElMessage.error('获取供应商信息失败');
    console.error('获取供应商信息错误:', error);
  }
};

// 处理产品选择变化
const handleProductSelectionChange = (selection: any[]) => {
  // 过滤掉已选中的产品
  const newProducts = selection
    .filter(item => !selectedProducts.value.some(p => p.productId === item.productId))
    .map(item => ({
      ...item,
      quantity: 1,
      totalPrice: item.price
    }));

     if (selection.length > 0) {
    const firstProduct = selection[0];
    purchaseForm.productName = firstProduct.productName;
    purchaseForm.productId = firstProduct.productId;
    purchaseForm.productSpecs = firstProduct.specifications; // 注意字段名是否匹配
    purchaseForm.unitId = firstProduct.unitId; // 需确认产品表格里的“单位ID”字段名
    purchaseForm.price = firstProduct.price;
    purchaseForm.num = 1; // 或从 newProducts 里取 quantity
    purchaseForm.total = firstProduct.price * 1; // 或直接用 firstProduct.totalPrice
  }

  // 添加新选中的产品
  selectedProducts.value = [...selectedProducts.value, ...newProducts];

  // 清除表格选中状态
  if (productTableRef.value) {
    productTableRef.value.clearSelection();
  }
};



// 移除选中的产品
const removeSelectedProduct = (productId: number) => {
  selectedProducts.value = selectedProducts.value.filter(p => p.productId !== productId);
};

import http from '@/http/axiosHelper';
import Check from '@/http/Check';
// 提交表单
const submitForm = async () => {
  if (!purchaseFormRef.value) return;

  try {
    await purchaseFormRef.value.validate();

    if (selectedProducts.value.length === 0) {
      ElMessage.warning('请至少选择一个产品');
      return;
    }

    // 调用API提交采购单
   http.post("/scmwriteconsul/api/Purchase/AddPurchase",purchaseForm).then(response=>{
     if (response.data.code == 200) {
      ElMessage.success(response.data.msg || '采购单添加成功');
     
    } else {
      ElMessage.error(response.data.msg);
    }
   })
   
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

// 重置表单
const resetForm = (clearProducts = true) => {
  if (purchaseFormRef.value) {
    purchaseFormRef.value.resetFields();
  }
 
  if (clearProducts) {
    selectedProducts.value = [];
  }
  
  
};

// 页面加载时获取产品列表
onMounted(async () => {
  await fetchProductList();
});
</script>

<style scoped>
.required-note {
  color: #ff4d4f;
  margin-bottom: 16px;
  text-align: right;
}

.basic-info-form {
  margin-bottom: 20px;
}

.product-list-section,
.selected-products-section {
  margin-bottom: 20px;
}

.no-products-tip {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.form-actions {
  text-align: center;
  margin-top: 20px;
}

.delete-btn {
  color: #ff4d4f;
}

::v-deep .el-table__header-wrapper th {
  background-color: #f5f7fa;
  font-weight: 500;
}
</style>